# -*- coding: utf-8 -*-
import hashlib
import json
from collections import OrderedDict

import requests
from django.conf import settings

from async import async_job
from common.order.db import get_pay, add_pay_success
from common.order.model import PAY_STATUS
from common.utils import track_logging
from common.utils.exceptions import ParamError

_LOGGER = track_logging.getLogger(__name__)

APP_CONF = {
    '10000373': {  # dwc  支付宝3%（10---3000），d0结算
        'API_KEY': 'AFA5EAC3F097BEB6309EAF2FA444303B',
        'gateway': 'http://pay.3v22.com/api/pay',
        'query_gateway': 'http://pay.3v22.com/api/orderquery?account={}&order={}&sign={}',
    },
    '10000558': {  # loki 支付宝3%（10---3000,10的倍数充值）D0结算
        'API_KEY': 'F8EC65C892B99CCFB701DAFA292F5530',
        'gateway': 'http://pay.3v22.com/api/pay',
        'query_gateway': 'http://pay.3v22.com/api/orderquery?account={}&order={}&sign={}',
    },
}


def _get_api_key(mch_id):
    return APP_CONF[mch_id]['API_KEY']


def _get_gateway(mch_id):
    return APP_CONF[mch_id]['gateway']


def _get_query_gateway(mch_id):
    return APP_CONF[mch_id]['query_gateway']


def generate_sign(d, key):
    s = 'account={}&callback={}&money={}&notify={}&order={}&paytype={}&{}'.format(
        d['account'], d['callback'], d['money'], d['notify'], d['order'], d['paytype'], key
    )
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    sign = m.hexdigest()
    return sign


def generate_notify_sign(d, key):
    s = 'account={}&money={}&order={}&orders={}&paytype={}&{}'.format(
        d['account'], d['money'], d['order'], d['orders'], d['paytype'], key
    )
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    sign = m.hexdigest()
    return sign


def generate_query_sign(d, key):
    s = 'account={}&order={}&{}'.format(
        d['account'], d['order'], key
    )
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    sign = m.hexdigest()
    return sign


def verify_notify_sign(params, key):
    sign = params.pop('sign')
    calculated_sign = generate_notify_sign(params, key)
    if sign != calculated_sign:
        _LOGGER.info("lezhifupay sign: %s, calculated sign: %s", sign, calculated_sign)
        raise ParamError('sign not pass, data: %s' % params)


# 微信 H5DO  wxh5d0
# 微信 H5D1  wxh5d1
# 微信 H5TO  wxh5t0
# 微信 H5T1  wxh5t1
# 微信扫码 D0 wxsmd0
# 微信扫码 D1 wxsmd1
# 微信扫码 T0 wxsmt0
# 微信扫码 T1 wxsmt1
# 支付宝扫码 D0 zfbsmd0
# 支付宝扫码 D1 zfbsmd1
# 支付宝扫码 T0 zfbsmt0
# 支付宝扫码 T1 zfbsmt1
# 支付宝 WAPD0 zfbwapd0
# 支付宝 WAPD1 zfbwapd1
# 支付宝 WAPT0 zfbwapt0
# 支付宝 WAPT1  zfbwapt1
# 快捷 D0 kjd0
# 快捷 D1 Kjd1
# 快捷 T0 kjt0
# 快捷 T1 Kjt1
def _get_pay_type(service):
    if service == 'wxpay':
        payType = 'wxh5d0'
    elif service == 'alipay':
        payType = 'zfbwapd0'
    else:
        payType = 'kjd0'
    return payType


def _get_device_ip(info):
    try:
        extra = json.loads(info['extra'])
    except:
        extra = {}
    user_info = extra.get('user_info', {})
    return user_info.get('device_ip') or '127.0.0.1'


def create_charge(pay, pay_amount, info):
    mch_id = info['app_id']
    service = info.get('service')
    key = _get_api_key(mch_id)
    parameter_dict = OrderedDict((
        ('account', mch_id),
        ('order', str(pay.id)),
        ('money', str(pay_amount)),
        ('paytype', _get_pay_type(service)),
        ('notify', '{}/pay/api/{}/lezhifupay/{}'.format(settings.NOTIFY_PREFIX, settings.NOTIFY_PATH, mch_id)),
        ('callback', '{}/pay/api/{}/lezhifupay/{}'.format(settings.NOTIFY_PREFIX, settings.RETURN_PATH, pay.id)),
        # ('ip', _get_device_ip(info)),
    ))
    parameter_dict['sign'] = generate_sign(parameter_dict, key)
    parameter_dict['ip'] = _get_device_ip(info)
    _LOGGER.info("lezhifupay create date: %s", parameter_dict)
    headers = {'Content-Type': 'application/x-www-form-urlencoded'}
    headers['api-key'] = key
    response = requests.post(_get_gateway(mch_id), data=parameter_dict, headers=headers, timeout=10)
    _LOGGER.info("lezhifupay create rsp data: %s", response.text)
    return {
        'charge_info': json.loads(response.text)['payurl'].replace('HTTPS://QR.ALIPAY.COM/', 'https://qr.alipay.com/')}


# success
def check_notify_sign(request, app_id):
    key = _get_api_key(app_id)
    data = dict(request.GET.iteritems())
    _LOGGER.info("lezhifupay notify body: %s", data)
    verify_notify_sign(data, key)
    pay_id = data['order']
    if not pay_id:
        _LOGGER.error("fatal error, pay object not exists, data: %s" % data)
        raise ParamError('lezhifupay event does not contain valid pay ID')

    pay = get_pay(pay_id)
    if not pay:
        raise ParamError('pay_id: %s invalid' % pay_id)
    if pay.status != PAY_STATUS.READY:
        raise ParamError('pay %s has been processed' % pay_id)

    mch_id = pay.mch_id
    trade_status = int(data['status'])
    trade_no = data['orders']
    total_fee = float(data['money'])

    extend = {
        'trade_status': trade_status,
        'trade_no': trade_no,
        'total_fee': total_fee
    }
    from common.channel.pay import check_channel_order
    check_channel_order(pay_id, total_fee, app_id)
    # 1为成功 其余为失败
    if trade_status == 1:
        _LOGGER.info('lezhifupay check order success, user_id:%s pay_id:%s' % (mch_id, pay_id))
        add_pay_success(mch_id, pay_id, total_fee, trade_no, extend)
        # async notify
        async_job.notify_mch(pay_id)


def query_charge(pay_order, app_id):
    pay_id = pay_order.id
    key = _get_api_key(app_id)
    p_dict = {
        'account': app_id,
        'order': str(pay_id),
    }
    p_dict['sign'] = generate_query_sign(p_dict, key)
    _LOGGER.info(u'lezhifupay query p_dict: %s', p_dict)
    headers = {}
    headers['api-key'] = key
    url = _get_query_gateway(app_id).format(p_dict['account'], p_dict['order'], p_dict['sign'])
    response = requests.get(url, headers=headers, timeout=10)
    _LOGGER.info(u'lezhifupay query rsp : %s', response.text)
    data = json.loads(response.text)['data']
    if response.status_code == 200:
        trade_status = int(data['paystatus'])  # 0 订单未成功 1订单成功
        total_fee = float(data['money'])
        trade_no = data['orders']
        extend = {
            'trade_status': trade_status,
            'trade_no': trade_no,
            'total_fee': total_fee
        }

        if trade_status == 1:
            _LOGGER.info('lezhifupay query order success, mch_id:%s pay_id:%s' % (pay_order.mch_id, pay_id))
            add_pay_success(pay_order.mch_id, pay_id, total_fee, trade_no, extend)
            async_job.notify_mch(pay_order.id)
    else:
        _LOGGER.warn('lezhifupay data error, status_code: %s', response.status_code)
